// ==UserScript==
// @name         alilang-小助手
// @namespace             https://gitee.com/monkeyshow/tm_scripts
// @supportURL            https://gitee.com/monkeyshow/tm_scripts
// @updateURL             https://gitee.com/monkeyshow/tm_scripts/raw/master/alilang/alilang-helper.js
// @downloadURL           https://gitee.com/monkeyshow/tm_scripts/raw/master/alilang/alilang-helper.js
// @version      0.1.0
// @description  alilang-小助手
// @author       jianjian.huang
// @match        *://op.alilang.com/*
// @grant        unsafeWindow
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_listValues
// @grant        GM_xmlhttpRequest
// @run-at       document-idle
// @require      https://cdn.staticfile.org/jquery/3.5.0/jquery.min.js
// ==/UserScript==
(() => {
  'use strict'
  const chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const chnUnitSection = ['', '万', '亿', '万亿', '亿亿'];
  const chnUnitChar = ['', '十', '百', '千'];
  const chnNumber = { 0: '零', 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '七', 8: '八', 9: '九' };
  const KEY_BOARD_CODE = { ENTER: 13, SPACE: 32, MINI_PLUS: 43, MINI_MINUS: 45, ZERO: 48, P: 80, R: 82, S: 83, W: 87 };
  const MouseClickEvent = document.createEvent("MouseEvents");
  const ElementEvent = document.createEvent("UIEvents");
  MouseClickEvent.initEvent("click", true, true);
  ElementEvent.initEvent("keydown", true, true);

  function getValue(name) {
    return GM_getValue(name);
  }

  function setValue(name, value) {
    GM_setValue(name, value);
  }

  function clog() {
    console.group('[alilang-小助手]')
    let args = Array.prototype.slice.call(arguments);
    args.forEach(element => {
      console.log(element);
    });
    console.groupEnd()
  }
  // 阿拉伯数字转汉字
  function NumberToChinese(num) {
    let unitPos = 0;
    let strIns = '', chnStr = '';
    let needZero = false;

    if (num === 0) {
      return chnNumChar[0];
    }

    while (num > 0) {
      let section = num % 10000;
      if (needZero) {
        chnStr = chnNumChar[0] + chnStr;
      }
      strIns = SectionToChinese(section);
      strIns += (section !== 0) ? chnUnitSection[unitPos] : chnUnitSection[0];
      chnStr = strIns + chnStr;
      needZero = (section < 1000) && (section > 0);
      num = Math.floor(num / 10000);
      unitPos++;
    }
    return chnStr;
  }
  function SectionToChinese(section) {
    let strIns = '', chnStr = '';
    let unitPos = 0;
    let zero = true;
    while (section > 0) {
      let v = section % 10;
      if (v === 0) {
        if (!zero) {
          zero = true;
          chnStr = chnNumChar[v] + chnStr;
        }
      } else {
        zero = false;
        strIns = chnNumChar[v];
        strIns += chnUnitChar[unitPos];
        chnStr = strIns + chnStr;
      }
      unitPos++;
      section = Math.floor(section / 10);
    }
    return chnStr;
  }
  // 阿拉伯数字转日期汉字
  function NumberToDate(num) {
    let chnStr = '';
    num = num.toString();
    for (let n in num) {
      chnStr += chnNumber[num[n]];
    }
    return chnStr;
  }
  function AlilangPlugin() {
    this.init = () => {
      this.addGMStyle()
      this.main()
    }

    this.main = () => {
      let $container = $('<div class="lh-container" id="dm-notif"></div>');
      // 按钮
      let $btn_trans_date = $('<button type="button" class="lh-btn">转换日期</button>');
      let $btn_trans_num = $('<button type="button" class="lh-btn">转换数字</button>');
      // 按钮外部的div
      let $btn_div = $("<div/>").append($btn_trans_date).append($btn_trans_num);
      $container.append($btn_div);
      //TODO 添加到页面中
      $('#页面选择器').append($container);

      /***************************************** 事件绑定 *****************************************/
      // 按钮事件绑定
      //TODO 找到对应的选择器
      let selector_link = '';
      let selector_editor = '';
      // 转换日期数字
      $btn_trans_date.click(() => {
        //1.先触发超链接【鼠标点击】事件
        $('超链接选择器').get(0).dispatchEvent(MouseClickEvent);
        //2.替换填充以后的字符串
        let oldStr = '';// 获取原始字符串
        let repStr = oldStr.replace(/\d+/g, function () {
          //调用方法时内部会产生 this 和 arguments
          console.log(arguments[0]);
          //查找数字后，可以对数字进行其他操作
          return NumberToDate(arguments[0]);
        });
        clog('替换日期:', repStr);
      });
      // 转换金额数字
      $btn_trans_num.click(() => {
        //1.先触发超链接【鼠标点击】事件
        $('超链接选择器').get(0).dispatchEvent(MouseClickEvent);
        //2.替换填充以后的字符串
        let oldStr = '';// 获取原始字符串
        let repStr = oldStr.replace(/\d+/g, function () {
          //调用方法时内部会产生 this 和 arguments
          console.log(arguments[0]);
          //查找数字后，可以对数字进行其他操作
          return NumberToChinese(arguments[0]);
        });
        clog('替换数字:', repStr);
      });
      //TODO 绑定快捷键
      $(document).keypress((e) => {
        let keyCode = e.keyCode || e.which || e.charCode;
        let altKey = e.altKey;
        let ctrlKey = e.ctrlKey;
        let shiftKey = e.shiftKey;
        clog(`document keypress: keycode=${e.keyCode},alt=${altKey},ctrl=${ctrlKey},shift=${shiftKey}`);
        // 整个文档接收到了快捷键操作
        if (keyCode == KEY_BOARD_CODE.SPACE && e.target.nodeName == 'TEXTAREA' && e.target.className == 'ant-input') {
          // this.trimCurrent();
        }
      });
    };
    this.addGMStyle = () => {
      GM_addStyle(`
        .lh-btn {color: #fff;background-color: #007bff;border-color: #007bff;padding: .375rem .75rem;border-radius: .25rem;}
        .lh-container {position: fixed;bottom: 5px;right: 5px;margin-left: 5px;z-index: 3000;width:226px;background-color:pink;overflow:hidden;}
        `)
    };
    // 自定义函数
    this.trimCurrent = () => {
      let $textarea = $('textarea.ant-input:focus');
      let oldStr = $textarea.parent().prev().text();
      let repStr = oldStr.replace(/\s+/g, "");
      clog(`old=${oldStr}-new=${repStr}`);
      $textarea.val(repStr);
      $textarea.get(0).dispatchEvent(ElementEvent);
    };
    // 测试代码，可以删除
    this.testReg = () => {
      var str = "去年是2014年，今年是2015年";
      // 正则表达式  /\d+/g： 匹配至少一个数字。
      var newStr = str.replace(/\d+/g, function () {
        //调用方法时内部会产生 this 和 arguments
        console.log(arguments[0]);
        //查找数字后，可以对数字进行其他操作
        return arguments[0] * 2;
      });
      // 需要取得的是数字 2014 和 2015，所以只要取得 arguments[0] 即可。
      console.log(newStr);
    }
  }
  // 启用插件
  if ($('#页面选择器').length) {
    clog('hello alilang!')
    let plugin = new AlilangPlugin();
    plugin.init();
  }
})();